package com.android.xunxian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.MyApplication;
import com.android.xunxian.R;
import com.android.xunxian.entry.GuanW;
import com.android.xunxian.entry.JLTable;
import com.android.xunxian.entry.JWdu;
import com.android.xunxian.entry.JWdu1;
import com.android.xunxian.entry.Xunx;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.android.xunxian.view.ActionSheetDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 邹啟华 on 2016/7/20.
 */
public class XunxMapActivity extends Activity implements View.OnClickListener {

    private MapView mapView;
    private ImageView close;
    private TextView title,img,sp,beiz,luy;
    private LinearLayout layout;

    BaiduMap mBaiduMap;
    BitmapDescriptor mRedTexture = BitmapDescriptorFactory.fromAsset("icon_road_red_arrow.png");
    BitmapDescriptor mBlueTexture = BitmapDescriptorFactory.fromAsset("icon_road_blue_arrow.png");
    // 纹理折线，点击时获取折线上点数及width
    Polyline mTexturePolyline;
    private String id;
    private List<JWdu> jWduList;
    private List<JWdu> jxlist;
    public String longitude;
    public String latitude;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;

    private String imgPath;
    private String fileName;
    private String type;
    private Dialog Jdialog;
    private String time;
    List<Xunx> list=null;
    private String  updateOff;

    private List<GuanW> guanwTypeList;

    private List<List<JWdu>> gwList;
    // 普通折线，点击时改变宽度
    Polyline mPolyline;
    private String selcet;//是否选中，本地保存
    private Util util;
    private String[] array;

    private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "bd09ll";
    private String logPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xunx_map_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        layout=(LinearLayout)findViewById(R.id.layout);
        img = (TextView) findViewById(R.id.img);
        sp = (TextView) findViewById(R.id.sp);
        beiz = (TextView) findViewById(R.id.beizhu);
        luy = (TextView) findViewById(R.id.luyin);
        mapView = (MapView) findViewById(R.id.mapView);
        mBaiduMap = mapView.getMap();
        util=new Util(this);
        logPath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/xunxian/";
        updateOff=util.getUser("off");
        jxlist=new ArrayList<>();
//         开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        title.setText("巡线查看");
        close.setOnClickListener(this);
        img.setOnClickListener(this);
        sp.setOnClickListener(this);
        luy.setOnClickListener(this);
        beiz.setOnClickListener(this);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
//        LocationClientOption option = new LocationClientOption();
//        option.setOpenGps(true); // 打开gps
//        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(1000);
        setLocationOption();
//        mLocClient.setLocOption(option);
        mLocClient.start();

            getYroute();

        guanwTypeList=new ArrayList<>();
        gwList=new ArrayList<>();
        selcet = util.getUser("guanw");
        System.out.println("selcet---" + selcet);
        if (Util.NoNull(selcet)) {


            if (selcet.contains(",")) {
                array = selcet.split(",");
            } else {
                array = new String[1];
                array[0] = selcet;
            }

        }

        try {

//            LatLng p111 = new LatLng(la,  lo);
//            MapStatus.Builder builder = new MapStatus.Builder();
//            builder.target(p111).zoom(13.0f);
//            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            jWduList = MyApplication.dbManager.selector(JWdu.class).findAll();
            if (array!=null){

                for (int i=0;i<array.length;i++){
                    List<GuanW> list= MyApplication.dbManager.selector(GuanW.class).where("LINEKIND","=",array[i]).findAll();
                    if (list!=null&&list.size()>0){
                        guanwTypeList.addAll(list);
                    }

                }
                System.out.println("guanwTypeList.size()---"+guanwTypeList.size());

            }
            getGwAll();
            setMap();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getYroute(){

        try {
           list = MyApplication.dbManager.selector(Xunx.class).where("SPLANZT", "=", "执行中").findAll();
            if (list != null && list.size() > 0) {
                title.setText(list.get(0).getNAME());
                imgPath = Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "Xunxian" + File.separator + list.get(0).getID() + File.separator;
                layout.setVisibility(View.VISIBLE);
                System.out.println("list---"+list);
                try {
                    if(Util.NoNull(list.get(0).getXXQY())){
                    JSONArray jsonArray=new JSONArray(list.get(0).getXXQY());
                    if (jsonArray.length()>0){
                        for (int i =0;i<jsonArray.length();i++){
                            Log.i("==============",jsonArray.getJSONArray(i).getString(0));
                            Log.i("-----------------",jsonArray.getJSONArray(i).getString(1));
                            JWdu jWdu=new JWdu();
                            jWdu.setLatitude(jsonArray.getJSONArray(i).getString(1));
                            jWdu.setLongitude(jsonArray.getJSONArray(i).getString(0));
                            jxlist.add(jWdu);
                        }
                    }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    private void getGwAll(){
        if (guanwTypeList.size()>0){
            for (int a=0;a<guanwTypeList.size();a++){
                List<JWdu> jWdus=new ArrayList<>();
                try {
                    JSONArray jsonArray = new JSONArray(guanwTypeList.get(a).getXYS());
                    if (jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            Log.i("qqqqqqqqq", jsonArray.getJSONArray(i).getString(0));
                            Log.i("bbbbbbbbbbbb", jsonArray.getJSONArray(i).getString(1));
                            JWdu jWdu = new JWdu();
                            jWdu.setLatitude(jsonArray.getJSONArray(i).getString(1));
                            jWdu.setLongitude(jsonArray.getJSONArray(i).getString(0));
                            jWdus.add(jWdu);
                        }
                        gwList.add(jWdus);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.img:
                Log.i("AAAAAAAAAAAAAAAAA", "拍照保存照片");
//                saveImg();
                type = "照片";

                showPickDialog();


                break;

            case R.id.sp:
                Log.i("AAAAAAAAAAAAAAAAA", "视频录像保存");
                type = "视频";

                showVdioDialog();
                break;

            case R.id.beizhu:
                Intent intenta = new Intent(this, RemarksActivity.class);
                intenta.putExtra("id", list.get(0).getID());
                startActivityForResult(intenta, 3);
                break;


            case R.id.luyin:
                Intent intent1 = new Intent(this, LuyinActivity.class);
                intent1.putExtra("id", list.get(0).getID());
                startActivityForResult(intent1, 4);
                break;
        }
    }


    private void setMap() {
        List<LatLng> points11 = new ArrayList<LatLng>();
        // 添加多纹理分段的折线绘制
        if (jWduList != null && jWduList.size() >1) {
            for (int i = 0; i < jWduList.size(); i++) {
                LatLng p111 = new LatLng(Double.parseDouble(jWduList.get(i).getLatitude()), Double.parseDouble(jWduList.get(i).getLongitude()));
                points11.add(p111);
            }

            List<BitmapDescriptor> textureList = new ArrayList<BitmapDescriptor>();
            textureList.add(mRedTexture);
            List<Integer> textureIndexs = new ArrayList<Integer>();
            textureIndexs.add(0);
            OverlayOptions ooPolyline11 = new PolylineOptions().width(10)
                    .points(points11).dottedLine(true).customTextureList(textureList).textureIndex(textureIndexs);
            mTexturePolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline11);
        }
        List<LatLng> points2 = new ArrayList<LatLng>();
        if (jxlist != null && jxlist.size() > 1) {
            System.out.println("AAAAAAAAAAAAAAAA");
            for (int j = 0; j < jxlist.size(); j++) {
                LatLng p = new LatLng(Double.parseDouble(jxlist.get(j).getLatitude()), Double.parseDouble(jxlist.get(j).getLongitude()));
                points2.add(p);
            }
            List<BitmapDescriptor> textureList1 = new ArrayList<BitmapDescriptor>();
            textureList1.add(mBlueTexture);
            List<Integer> textureIndexs1 = new ArrayList<Integer>();
            textureIndexs1.add(0);
            OverlayOptions ooPolyline2 = new PolylineOptions().width(10)
                    .points(points2).dottedLine(true).customTextureList(textureList1).textureIndex(textureIndexs1);
            mTexturePolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline2);

        }

        if (gwList.size()>0){
            for (int k=0;k<gwList.size();k++){
                List<LatLng> points = new ArrayList<LatLng>();
                for (int g=0;g<gwList.get(k).size();g++){
                    LatLng p = new LatLng(Double.parseDouble(gwList.get(k).get(g).getLatitude()), Double.parseDouble(gwList.get(k).get(g).getLongitude()));
                    points.add(p);
                }

                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                        .color(Color.parseColor(guanwTypeList.get(k).getLINECOLOR())).points(points);
                mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);


            }
        }



        mapView.refreshDrawableState();


    }


    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        mRedTexture.recycle();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        if (mLocClient != null && mLocClient.isStarted()) {
            mLocClient.stop();
        }
        super.onDestroy();
    }


    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        // TODO Auto-generated method stub
        option.setLocationMode(tempMode);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);// 可选，默认gcj02，设置返回的定位结果坐标系，
        int span = 1000 * UConstants.TIME;
        System.out.println("span---"+span);
        option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(false);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(false);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocClient.setLocOption(option);

    }


/**
    * 定位SDK监听函数
    */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location != null) {
                Log.i("bbbbb", location.getLongitude() + "");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String time = dateFormat.format(new Date());
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (location != null) {
                    longitude = location.getLongitude() + "";
                    latitude = location.getLatitude() + "";
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(15.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//                mLocClient.stop();
                    if (list != null && list.size() > 0) {
                        JWdu jWdu = new JWdu();
                        jWdu.setLatitude(latitude);
                        jWdu.setLongitude(longitude);
                        jWdu.setXXId(list.get(0).getXXId());
                        jWdu.setTime(time);
                        JWdu1 jWdu1 = new JWdu1();
                        jWdu1.setLatitude(latitude);
                        jWdu1.setLongitude(longitude);
                        jWdu1.setXXId(list.get(0).getXXId());
                        jWdu1.setTime(time);
                        try {
                            MyApplication.dbManager.save(jWdu);
                            MyApplication.dbManager.save(jWdu1);
                            List<JWdu1> list = MyApplication.dbManager.selector(JWdu1.class).findAll();
                            if (list != null && list.size() > 0) {
                                Log.i("list==size", list.size() + "");
                                Gson gson = new Gson();
                                String json = gson.toJson(list);//将更新数组
                                String str = "{\"success\":\"true\", \"rows\":" + json + "}";
                                util.writeTxtToFile(str,logPath,"xunxianLog.txt");
                                updateGPS(str);
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
//                    else{
//                        mLocClient.stop();
//                    }
                }
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }


    //上传路线
    private void updateGPS(final String mar) {
//        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        RequestParams params = new RequestParams(UConstants.UPDATE_GPS);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("Data", mar);
//
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            try {
                                MyApplication.dbManager.delete(JWdu1.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

//                Toast.makeText(x.app(), "地址错误或服务器无法连接！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

//                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
            }

            @Override
            public void onFinished() {

            }
        });
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    pointDialog("请输入文件说明", 1);
                    break;
            }
        }
    };

    /**
     * 提示
     */
    private void pointDialog(String str, int flag) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        final EditText text = (EditText) layout.findViewById(R.id.text);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                saveJL(text.getText().toString());
                Log.i("文件记录保存完成", "============");
                Jdialog.cancel();


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                saveJL(text.getText().toString());
                Log.i("文件记录保存完成", "============");
                Jdialog.cancel();
            }
        });

    }

    private void saveJL(String str) {
        JLTable jlTable = new JLTable();
        jlTable.setLatitude(latitude);
        jlTable.setLongitude(longitude);
        jlTable.setId(list.get(0).getID());
        jlTable.setFileKind(type);
        jlTable.setFileDt(time);
        jlTable.setFileName(fileName);
        jlTable.setXXId(list.get(0).getXXId());
        jlTable.setFileMemo(str);
        try {
            MyApplication.dbManager.save(jlTable);

        } catch (DbException e) {
            e.printStackTrace();
        }

        if (Util.NoNull(updateOff)&&updateOff.equals("1")){
            upDate(jlTable);
        }

    }

    //保存图片
    private void saveImg() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            Date nowTime = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                    "yyyyMMddHHmmss");
            time = simpleDateFormat.format(nowTime);
            fileName = list.get(0).getID() + "_" + time + ".jpg";
            Log.e("picPath--------", imgPath + fileName);
            if (!new File(imgPath).exists()) {
                new File(imgPath).mkdirs();// 创建文件夹
            }
//             Intent intent = new
//             Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//             startActivityForResult(intent, 1);
            Intent openCameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            Uri imageUri = Uri.fromFile(new File(imgPath + fileName));
            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            openCameraIntent
                    .putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(openCameraIntent, 1);
        } else {
            Toast.makeText(this, "请先安装好sd卡",
                    Toast.LENGTH_SHORT).show();
        }
    }

    //录制视频
    private void saveVodie() {
        Intent intent = new Intent();
        intent.setAction("android.media.action.VIDEO_CAPTURE");
        intent.addCategory("android.intent.category.DEFAULT");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyyMMddHHmmss");
        time = simpleDateFormat.format(new Date());
        fileName = list.get(0).getID() + "_" + time + ".MP4";
        File file = new File(imgPath + fileName);
        if (file.exists()) {
            file.delete();
        }
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 2);
    }

    private Uri mPhotoUri = null;

    //选择图片
    void showPickDialog() {
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        saveImg();
                                    }
                                }).start();

                            }
                        })
                .addSheetItem("相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent(Intent.ACTION_PICK,
                                        null);
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image/*");
                                startActivityForResult(intent,
                                        5);
                            }
                        }).show();
    }


    //选择视频
    void showVdioDialog() {
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("开始录像", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                saveVodie();

                            }
                        })
                .addSheetItem("选择录像", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT,
                                        null);
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "video/*");
                                startActivityForResult(intent,
                                        6);
                            }
                        }).show();
    }


    private String getPhotoPath(Context context, Uri photoUri, Intent data) {
        String photoPath = "";
        ContentResolver cr = context.getContentResolver();
        if (photoUri != null) {
            Cursor cursor = cr.query(photoUri, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                int pathIndex = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                photoPath = cursor.getString(pathIndex);
                cursor.close();
            }
        } else {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    photoPath = uri.getPath();
                    if (!(new File(photoPath).exists())) {
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor actualimagecursor = cr.query(uri, proj, null,
                                null, null);
                        int actualImg = actualimagecursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToFirst();
                        if (actualimagecursor != null)
                            photoPath = actualimagecursor.getString(actualImg);
                    }
                }
            }
        }
        return photoPath;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                Bitmap bitmap = BitmapFactory.decodeFile(
                        imgPath + fileName, options);
                FileOutputStream b = null;
                try {
                    b = new FileOutputStream(imgPath + fileName);
                    if (b != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                        handler.sendEmptyMessage(1);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (b != null) {
                            b.flush();
                            b.close();
                            bitmap.recycle();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (requestCode == 2) {
            if (data != null)
                handler.sendEmptyMessage(1);
        } else if (requestCode == 3) {
            Log.i("DeilstXunxActivity===", "保存备注");
            if (data != null) {
                time = data.getStringExtra("time");
                fileName = data.getStringExtra("name");
                type = "备注";
                handler.sendEmptyMessage(1);
            }

        } else if (requestCode == 4) {
            Log.i("DeilstXunxActivity===", "保存备注");
            if (data != null) {
                time = data.getStringExtra("time");
                fileName = data.getStringExtra("name");
                type = "录音";
                handler.sendEmptyMessage(1);
            }

        } else if (requestCode == 5) {
            Log.i("DeilstXunxActivity===", "相册选择");
            if (data != null) {


                String photoPath = getPhotoPath(this, mPhotoUri, data);


                Date nowTime = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                time = simpleDateFormat.format(nowTime);
                fileName = list.get(0).getID() + "_" + time + ".jpg";
                Log.e("picPath--------", imgPath + fileName);
                if (!new File(imgPath).exists()) {
                    new File(imgPath).mkdirs();// 创建文件夹
                }
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                Bitmap bitmap = BitmapFactory.decodeFile(
                        photoPath, options);

                FileOutputStream b = null;
                try {
                    b = new FileOutputStream(imgPath + fileName);
                    if (b != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                        handler.sendEmptyMessage(1);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (b != null) {
                            b.flush();
                            b.close();
                            bitmap.recycle();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {

            }


        } else if (requestCode == 6) {

            if (data != null) {

                String photoPath = getPhotoPath(this, mPhotoUri, data);
                Log.i("DeilstXunxActivity===", photoPath);
                Date nowTime = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                time = simpleDateFormat.format(nowTime);
                fileName = list.get(0).getID() + "_" + time + ".MP4";
                Log.e("picPath--------", imgPath + fileName);
                copyfile(new File(photoPath), new File(imgPath + fileName), true);
                handler.sendEmptyMessage(1);
            }
        }
    }


    public static void copyfile(File fromFile, File toFile, Boolean rewrite)

    {

        if (!fromFile.exists()) {

            return;

        }

        if (!fromFile.isFile()) {

            return;

        }

        if (!fromFile.canRead()) {
            return;

        }

        if (!toFile.getParentFile().exists()) {

            toFile.getParentFile().mkdirs();

        }

        if (toFile.exists() && rewrite) {

            toFile.delete();

        }

        //当文件不存时，canWrite一直返回的都是false


        try {

            FileInputStream fosfrom = new FileInputStream(fromFile);

            FileOutputStream fosto = new FileOutputStream(toFile);

            byte bt[] = new byte[1024];

            int c;

            while ((c = fosfrom.read(bt)) > 0) {

                fosto.write(bt, 0, c); //将内容写到新文件当中

            }

            fosfrom.close();

            fosto.close();

        } catch (Exception ex) {

            Log.e("readfile", ex.getMessage());

        }

    }

    ProgressDialog dialog;
    //获取巡线列表
    private void upDate(final JLTable jl) {
        if (jl==null){
            return;
        }
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
//

        if (!new File(imgPath+jl.getFileName()).exists()){
            dialog.dismiss();
            Toast.makeText(x.app(), "文件不存在！", Toast.LENGTH_SHORT).show();
            return;
        }

        List<JLTable> jlTableList=new ArrayList<>();
        jlTableList.add(jl);
        Gson gson = new Gson();
        String json1=gson.toJson(jlTableList);//将更新数组
        Log.i("BBBBBBBBBBBBBB",json1);
        String info  ="{\"success\":\"true\", \"total\":\""+jlTableList.size()+"\",\"rows\":"+json1+"}";

        RequestParams params = new RequestParams(UConstants.XX_UPDATE);
//
        params.addBodyParameter("LKind","CBJ");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("PartId", UConstants.PartId );
        params.addBodyParameter("FileInfo",info);

        params.addBodyParameter("FILES", new File(imgPath+jl.getFileName()));



        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
//                        allPage = Integer.parseInt(object.getString("total"));
//                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_SHORT).show();

                            new File(imgPath+jl.getFileName()).delete();
                            WhereBuilder b = WhereBuilder.b();
                            b.and("FileName","=",jl.getFileName()); //构造修改的条件
                            try {
                                MyApplication.dbManager.delete(JLTable.class,b);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }


                        } else {
                            Toast.makeText(x.app(), "上传失败,请手动上传！", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "上传失败,请手动上传！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
